<template>
  <div class="setting-info">
    <div class="custom-title setting-info-title">个人信息</div>
    <div class="setting-info-box">
      <el-descriptions :column="1">
        <template #extra>
          <el-button color="#D6000F" @click="handleCommand('update', $event)">修改密码</el-button>
        </template>
        <el-descriptions-item label="头像"> <el-avatar shape="square" :size="40" :src="avatar" /></el-descriptions-item>
        <el-descriptions-item label="客户ID">{{ id }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ userInfo.nickname }}</el-descriptions-item>
        <el-descriptions-item label="客户账号">{{ userInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="客户手机号">{{ userInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">{{ userInfo.state ? '启用' : '禁用' }}</el-descriptions-item>
        <el-descriptions-item label="客户所属区域">{{ userInfo.iterms.areaIdName }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <custom-dialog title="修改密码" width="600" custom-class="custom-web" v-model="state.isVisible"
      :disabled="state.disabled" @close="handleCommand('close', $event)">
      <el-form ref="codeFormRef" label-width="100px" :model="codeForm" :rules="codeRules">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="codeForm.phone" size="large" auto-complete="off" readonly placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item label="图形验证码" prop="imageCode">
          <div style="display: flex; align-items: center;width: 100%;">
            <el-input v-model="codeForm.imageCode" size="large" auto-complete="off" placeholder="图形验证码" style="flex: 1">
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode()" class="login-code-img" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="手机验证码" prop="code">
          <div style="display: flex; align-items: center;width: 100%;">
            <el-input v-model="codeForm.code" size="large" auto-complete="off" placeholder="请输入手机验证码">
            </el-input>
            <el-button size="large" color="#D6000F" style="margin-left: 10px;" :loading="sendPhoneCode"
              :disabled="isNotSendCode" @click.prevent="codeFormSubmit">{{ btnTxt }}</el-button>
          </div>
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="codeForm.oldPwd" size="large" type="password" show-password auto-complete="off" placeholder="请输入旧密码">
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="pwd">
          <el-input v-model="codeForm.pwd" size="large" type="password" show-password auto-complete="off" placeholder="请输入新密码">
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rePwd">
          <el-input v-model="codeForm.rePwd" size="large" type="password" show-password auto-complete="off" placeholder="请输入确认密码">
          </el-input>
        </el-form-item>
        <el-button size="large" color="#D6000F" style="width:100%;margin-top: 20px;" :loading="resetLoading"
          @click.prevent="resetFormSubmit">确定</el-button>
      </el-form>
    </custom-dialog>
  </div>
</template>

<script setup name="setting">
import { appPersonalGetInfoGet, appPersonalUpdatePwdPost } from '@/api/account'
import { getCodeImg } from "@/api/login";
import { appLoginSendPhonePost } from "@/api/forgetPassword";
import useUserStore from '@/store/modules/user'
import { computed } from 'vue';

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const { userInfo, id, name, avatar } = userStore
const state = reactive({
  isVisible: false,
  disabled: true,
})
const handleCommand = (type, e) => {
  if (type === 'close') {
    state.isVisible = false
  } else if (type === 'update') {
    state.isVisible = true
  }
}
const codeUrl = ref("");
function getCode (i) {
  getCodeImg().then(res => {
    codeUrl.value = "data:image/gif;base64," + res.img;
    codeForm.uuid = res.uuid;
  });
}
const codeForm = reactive({ //  - appLoginSendPhonePost body查询参数 appLoginSendPhonePostBody -body
  phone: userInfo.phone, // 手机号 string-body
  imageCode: '', // 验证码（和登录一样） string-body
  uuid: '', // 验证码唯一标示（和登录一样） string-body
  oldPwd: '', // 旧密码 string-body
  code: '', // 手机验证码 string-body
  pwd: '', // 密码 string-body
  rePwd: '' // 确认密码 string-body
})
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!/^(?=.*\d)(?=.*[a-zA-Z]).{6,18}$/.test(value)) {
    callback(new Error('密码至少有字母+数字，长度6 ~ 18位'))
  } else {
    if (codeForm.rePwd !== '') {
      if (!codeFormRef.value) return
      codeFormRef.value.validateField('rePwd')
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请重新输入确认密码'))
  } else if (value !== codeForm.pwd) {
    callback(new Error("两个输入不匹配！"))
  } else {
    callback()
  }
}
const codeRules = {
  phone: [
    { required: true, trigger: "blur", message: "请输入手机号" },
    { pattern: /^1[3456789]\d{9}$/, trigger: "blur", message: "手机号格式错误" }
  ],
  imageCode: [{ required: true, trigger: "change", message: "请输入图形验证码" }],
  code: [{ required: true, trigger: "change", message: "请输入手机验证码" }],
  oldPwd: [{ required: true, trigger: "blur", message: "请输入旧密码" }],
  pwd: [{ required: true, trigger: "blur", validator: validatePass }],
  rePwd: [{ required: true, trigger: "blur", validator: validatePass2 }]
}
getCode()
const sendPhoneCode = ref(false)
const codeFormRef = ref(null)
const countdown = ref(0);
const countdownInterval = ref(null);
const isNotSendCode = computed(() => countdown.value > 0 || codeForm.imageCode === '');
const btnTxt = computed(() => codeForm.imageCode === '' || countdown.value === 0 ? '发送验证码' : `${countdown.value} 秒`);
const clearTimeInterval = () => {
  // 清除之前的间隔计时器（如果有）
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value)
    countdownInterval.value = null
  }
};
const codeFormSubmit = () => {
  sendPhoneCode.value = true
  // 发送验证码
  appLoginSendPhonePost({ body: { phone: codeForm.phone, code: codeForm.imageCode, uuid: codeForm.uuid } }).then(res => {
    proxy.$modal.msgSuccess('验证码发送成功！')
    sendPhoneCode.value = false
    // 设置倒计时时间，例如60秒
    countdown.value = 60;
    clearTimeInterval()
    // 创建新的间隔计时器
    countdownInterval.value = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearTimeInterval() // 停止计时器
      }
    }, 1000);
  }).catch(() => {
    getCode()
    codeForm.imageCode = ''
    sendPhoneCode.value = false
  })
}
const resetLoading = ref(false)
const resetFormSubmit = () => {
  codeFormRef.value.validate((valid) => {
    if (valid) {
      // 重置密码
      resetLoading.value = true
      appPersonalUpdatePwdPost({
        body: {
          code: codeForm.code, // 手机验证码 string-body
          oldPwd: codeForm.oldPwd, // 旧密码 string-body
          phone: codeForm.phone, // 手机号 string-body
          pwd: codeForm.pwd // 密码 string-body
        }
      }).then(res => {
        resetLoading.value = false
        proxy.$modal.msgSuccess('密码修改成功！')
        userStore.logOut().then(() => {
          location.href = '/';
        })
      }).catch(() => {
        resetLoading.value = false
      })
    }
  })
}
appPersonalGetInfoGet().then((res) => {
  console.log('res', res)
})
</script>

<style lang="scss" scoped>
.setting-info {
  width: 100%;

  &-title {
    font-size: var(--jbc-font-size-extra-large);
  }

  .setting-info-box {
    margin-top: 20px;
    border: 1px solid #EBEBEB;
    padding: 30px;
  }
}

.login-code {
  display: inline-block;
  height: 40px;
  margin-left: 10px;

  .login-code-img {
    height: 40px;
  }
}
</style>